/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.questetra.bpms.android;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class StatsWidgetProvider extends AppWidgetProvider {
	// log tag
	private static final String TAG = StatsWidgetProvider.class.getSimpleName();

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		Log.d(TAG, "onUpdate");
		// Toast toast = Toast.makeText(context,
		// "widget.onUpdate()",
		// Toast.LENGTH_SHORT);
		// toast.show();

		setupButton(context, appWidgetManager, appWidgetIds);

		try {
			OAuthService.getInstance().setup(context);
		} catch (NoSettingsException e) {
			return;
		} catch (NoAccessTokenException e) {
			return;
		}

		Intent serviceIntent = new Intent(context, StatsService.class);
		context.startService(serviceIntent);
	}

	/**
	 * ボタンのセットアップ
	 * 
	 * @param context
	 * @param appWidgetManager
	 * @param appWidgetIds
	 */
	private void setupButton(Context context,
			AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		Intent intent = new Intent(context, WorkitemListActivity.class);
		PendingIntent operation = PendingIntent.getActivity(context, 0, intent,
				0);
		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.stats_widget);
		remoteViews
				.setOnClickPendingIntent(R.id.stats_widget_button, operation);
		appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
	}

	/**
	 * タスク数を取得してウィジェットに表示するサービス
	 * 
	 * @author akihiro
	 */
	public static class StatsService extends Service {
		@Override
		public void onStart(Intent intent, int startId) {
			Log.i(TAG, "onStart()");
			// Toast toast = Toast.makeText(this,
			// "service.onStart()",
			// Toast.LENGTH_SHORT);
			// toast.show();

			ComponentName thisWidget = new ComponentName(this,
					StatsWidgetProvider.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(this);
			if (manager.getAppWidgetIds(thisWidget).length == 0) {
				Log.i(TAG, "no widget");
				// toast = Toast.makeText(this, "no widget",
				// Toast.LENGTH_SHORT);
				// toast.show();
				return;
			}

			String url = "/API/PE/Workitem/statistics";
			StringBuilder builder = new StringBuilder();
			try {
				OAuthService service = OAuthService.getInstance();
				final String json = service.getResponse(url);
				JSONObject root = new JSONObject(json)
						.getJSONObject("statistics");
				builder.append(getText(R.string.workitem_list_allocated))
						.append(" ").append(root.getInt("allocated"));
				builder.append("  ").append(
						getText(R.string.workitem_list_offered)).append(" ")
						.append(root.getInt("offered"));
			} catch (IOException e) {
				Log.e(TAG, e.getMessage(), e);
				// toast = Toast.makeText(this, e.getMessage(),
				// Toast.LENGTH_LONG);
				// toast.show();
				setAlarm(1000 * 60 * 60);
				return;
			} catch (JSONException e) {
				Log.e(TAG, e.getMessage(), e);
				// toast = Toast.makeText(this, e.getMessage(),
				// Toast.LENGTH_LONG);
				// toast.show();
				setAlarm(1000 * 60 * 60);
				return;
			}

			RemoteViews remoteViews = new RemoteViews(getPackageName(),
					R.layout.stats_widget);
			remoteViews.setTextViewText(R.id.stats_widget_text, builder
					.toString());

			manager.updateAppWidget(thisWidget, remoteViews);
			setAlarm(1000 * 60 * 15);
		}

		private void setAlarm(long interval) {
			Intent alarmIntent = new Intent(this, StatsService.class);
			PendingIntent operation = PendingIntent.getService(this, 0,
					alarmIntent, 0);
			AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			long next = System.currentTimeMillis() + interval;
			am.set(AlarmManager.RTC, next, operation);
		}

		public static void reset(Context context) {
			Intent alarmIntent = new Intent(context, StatsService.class);
			PendingIntent operation = PendingIntent.getService(context, 0,
					alarmIntent, 0);
			AlarmManager am = (AlarmManager) context
					.getSystemService(Context.ALARM_SERVICE);
			am.cancel(operation);

			RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
					R.layout.stats_widget);
			remoteViews.setTextViewText(R.id.stats_widget_text, context
					.getText(R.string.msg_loading));

			ComponentName thisWidget = new ComponentName(context,
					StatsWidgetProvider.class);
			AppWidgetManager manager = AppWidgetManager.getInstance(context);
			manager.updateAppWidget(thisWidget, remoteViews);
		}

		@Override
		public IBinder onBind(Intent intent) {
			return null;
		}
	}
}
